package com.darkness.rpc.framework.protocol.dark;

import com.darkness.rpc.framework.common.Invocation;
import com.darkness.rpc.registercenter.local.LocalRegister;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * @author darkness
 * @time 2022/4/15 13:09
 * @description
 */
public class DarkProtocolHandler extends SimpleChannelInboundHandler<Invocation> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Invocation invocation) throws Exception {
        String interfaceName = invocation.getInterfaceName();
        String methodName = invocation.getMethodName();
        Class<?>[] paramTypes = invocation.getParamTypes();
        Object[] args = invocation.getArgs();
        Class<?> implClass = LocalRegister.getImplClass(invocation.getGroup(), interfaceName, invocation.getVersion());
        Class<?> aClass = Class.forName(interfaceName);
        Method method = aClass.getMethod(methodName, paramTypes);
        Serializable result = (Serializable) method.invoke(implClass.newInstance(), args);
        ctx.writeAndFlush(result);
    }
}
